package pers.crayon.baseprogram.sign.tools;

import lombok.extern.slf4j.Slf4j;
import pers.crayon.baseprogram.util.EncodeUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * MD5 签名工具类
 */
@Slf4j
public class MD5Signature {


    private MD5Signature() {
    }

    public static final String ALGORITHMS = "MD5";

    /**
     * rsa 签名
     *
     * @param content 待签名内容
     * @param key     私钥
     * @return
     */
    public static String sign(String content, String key) {
        try {
            MessageDigest md5 = MessageDigest.getInstance(ALGORITHMS);
            byte[] data = md5.digest((content + key).getBytes(StandardCharsets.UTF_8.name()));
            return EncodeUtils.encryptBASE64(data);
        } catch (Exception e) {
            log.error("[MD5_SIGN]: error={}", e.getMessage());
            return null;
        }
    }

    /**
     * MD5 验签名检查
     *
     * @param content 待签名数据
     * @param sign    签名值
     * @param key     分配给开发商公钥
     * @return 布尔值
     */
    public static boolean doCheck(String content, String sign, String key) {
        try {
            MessageDigest md5 = MessageDigest.getInstance(ALGORITHMS);
            byte[] data = md5.digest((content + key).getBytes(StandardCharsets.UTF_8.name()));
            String mysign = EncodeUtils.encryptBASE64(data);
            return mysign.equals(sign);
        } catch (Exception e) {
            log.error("[RSA_DO_CHECK]: error={}", e.getMessage());
            return false;
        }
    }
}
